/* ***** BEGIN LICENSE BLOCK *****
 *   Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is moodmill.
 *
 * The Initial Developer of the Original Code is
 * Akhmad Fathonih.
 * Portions created by the Initial Developer are Copyright (C) 2007
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

if (!moodmill) // ifdef ;), include_once
{

function MoodMill() {}

MoodMill.prototype = {
   messages: new Array(),
   arrMood: new Array('bad mood', 'low spirit', 'hmm', 'high spirit', 'excited'),
   curMood: 3,
   retries: 0,
   authObj: null,
  onLoad: function() {
    // initialization code
    this.initialized = true;
    this.strings = document.getElementById("moodmill-strings");
    
    if (this.isInstalled())
        this.upgrade();
    else
        this.showInstallDialog(); // install

    this.loggedIn = false;
    
    var oldUserName = YAHOO.MoodMill.Preference.getString('extensions.moodmill.username', null);
    if (this.getUser()!=null) {
      // isntalled, need update
      this.login(this.getUser(), this.getPass(), false);
      this.getCurMood();
    } else {
     // nto isntalled
      this.showPrefs();
    }
  },
  getUser: function() {
      //return YAHOO.MoodMill.Preference.getString('extensions.moodmill.username', null);
      var auth = this.getAuthObject();
      if (auth)
        return auth.user;
      else
        return null;
  },
  getPass: function() {
      //return YAHOO.MoodMill.Preference.getString('extensions.moodmill.password', null);
      var auth = this.getAuthObject();
      if (auth)
        return auth.password;
      else
        return null;
  },
  onMenuItemCommand: function(e) {
    var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
                                  .getService(Components.interfaces.nsIPromptService);
    promptService.alert(window, this.strings.getString("helloMessageTitle"),
                                this.strings.getString("helloMessage"));
  },
  updateMoodBar: function(e) {
    var idx = /moodmill-moodbar-(\d)/.exec(e.target.id);
    if (idx)
      this.showMood(idx[1]);
  },
  showMoodbar: function(pos) {
      var moodbar = document.getElementById('moodmill-moodbar-' + pos);
      moodbar.style.backgroundPosition= '-' + (pos-1)*30 + 'px' + ' -30px';
  },
  hideMoodbar: function(pos) {
      var moodbar = document.getElementById('moodmill-moodbar-' + pos);
      moodbar.style.backgroundPosition= '-' + (pos-1)*30 + 'px' + ' 0px';
  },
  mouseleave: function(e) {
//     var moodbar = document.getElementById('moodmill-moodbar');
//     moodbar.style.height= '15px';
  },
  action: function(e) {
      var idx = /moodmill-moodbar-(\d)/.exec(e.target.id);
      var mood_rate = idx[1];

      var features = "resizeable=yes,titlebar,toolbar,centerscreen,modal,height=250,width=500";
      var url = "chrome://moodmill/content/mooddlg.xul";
      var params = {'input':{'rate': mood_rate}, 'output':null};
      window.openDialog(url, "moodmill", features, params).focus();
      if (params.output != null) {
         this.postMood(params.output.rate, params.output.desc, params.output.url);
      } else {
         Logger.log('no mood submission');
      }
  },
  postMood: function(mood_rate, mood_desc, mood_url) {
      Logger.log("Posting your mood\nMood Rate: "+mood_rate+"\nMood Desc: "+mood_desc+"\nMood URL: " + mood_url);
      this.cacheMood(mood_rate, mood_desc, mood_url);

      var url = 'http://www.moodmill.com/ajax.php';
      var postdata = 'act=mood_submit&mood-rate=' + mood_rate + '&mood-desc=' + escape(mood_desc) + '&mood-url=' + escape(mood_url);
      this.showProgress();
      YAHOO.util.Connect.resetDefaultHeaders();
      YAHOO.util.Connect.setDefaultPostHeader(false);
      YAHOO.util.Connect.initHeader('Content-Type', 'application/x-www-form-urlencoded');
      YAHOO.util.Connect.asyncRequest('POST', url , {success: this.handleSuccess ,failure:function(o){this.appendMessage('Error: ' + o.statusText + "\n" + o.responseText)}, argument: {'mood': mood_rate}, scope: this}, postdata);
  },
  handleSuccess: function(o) {
      //alert(o.responseText);
      this.stopProgress();
      if (/Sorry,/.test(o.responseText)) {
         //alert('Sorry, you need to login first (manually) to moodmill.com');
         this.retry();
      } else {
         this.appendMessage("Yipeee\n" + o.responseText);
         this.cacheAvailable = false; // invalidate mood cache
         this.curMood = this.cacheMoodRate;
         this.showCurMood();
      }
  },
  getCurMood: function() {
      Logger.log('getCurMood for user: ' + this.getUser());
      var url = 'http://www.moodmill.com/rss/' + this.getUser() + '/?' + Math.random();
      this.showProgress();
      YAHOO.util.Connect.asyncRequest('GET', url , {success: this.handleCurMood ,failure:function(o){this.stopProgress(); this.appendMessage('Error retrieving current mood: ' + o.statusText + "\n" + o.responseText)}, scope: this});
  },
  handleCurMood: function(o) {
      //Logger.log('Reponse mood: ' + o.responseText);
      var cur_mood = /<title>.*?\[(.*?)\].*?<\/title>/.exec(o.responseText);
      Logger.log('Current mood: ' + cur_mood);
      var mood_rate = 3;
      //Logger.log(this.arrMood.length);
      var len = this.arrMood.length;
      for(var i=0;i<len;i++) {
         var re = new RegExp(this.arrMood[i], 'i');
         Logger.log("testing: " + this.arrMood[i] + " in " + cur_mood[1]);
         if (re.test(cur_mood[1])) {
            mood_rate = i+1;
            break;
         }
      }
      Logger.log('Got mood_rate: ' + mood_rate);
      this.curMood = mood_rate;
      this.showMood(mood_rate);
      this.stopProgress();
  },
  cacheMood: function(rate, desc, url) {
      this.cacheAvailable = true;
      this.cacheMoodRate = rate;
      this.cacheMoodDesc = desc;
      this.cacheMoodUrl = url;
  },
  login: function(user, pass, callback) {
      Logger.log('Logging you in, hold tight ...');
      //f_id=neofreko&f_password=xxx&f_submit.x=33&f_submit.y=8&f_submit=Submit
      //http://www.moodmill.com/login/next//
      var url = 'http://www.moodmill.com/login/next//';
      var postdata = 'f_id=' + user + '&f_password=' + pass + '&f_submit.x=33&f_submit.y=8&f_submit=Submit';
      this.showProgress();
      YAHOO.util.Connect.asyncRequest('POST', url , {success: function(o) {this.stopProgress();this.loggedIn = true; if (callback) callback(); Logger.log('Logged in ^^. Yattaaa ...');} ,failure:function(o){this.stopProgress(); this.appendMessage('Error: ' + o.statusText + "\n" + "\nUnable to login using current user/pass\n" + o.responseText)}, scope: this}, postdata);
  },
  retry: function() {
      if (this.retries > 10) {
         Logger.log('Reached maximum retries! Stopping.');
         this.retries = 0;
         return;
      }
      Logger.log('Retry #' + this.retries);
      this.login(this.getUser(), this.getPass(), function() {this.postMood(this.cacheMoodRate, this.cacheMoodDesc, this.cacheMoodUrl);});
  },
  showMood: function(mood) {
      //Logger.log('ShowMood: ' + mood);
      for(var i=1;i<=5;i++) {
         if (i>mood)
            this.hideMoodbar(i);
         else
            this.showMoodbar(i);
      }
  },
  showCurMood: function() {
      Logger.log('ShowCurMood: ' + this.curMood);
      this.showMood(this.curMood);
  },
  showProgress: function() {
      var progress = document.getElementById('moodmill-config-image');
      progress.src = 'chrome://moodmill/skin/ajax-loading-small.gif';
  },
  stopProgress: function() {
      var progress = document.getElementById('moodmill-config-image');
      progress.src = 'chrome://moodmill/skin/statusbar.png';
  },
  showPrefs: function() {
      var features = "resizeable=yes,titlebar,toolbar,centerscreen,modal";
      var url = "chrome://moodmill/content/wizard.xul";
      window.openDialog(url, "moodmill_pref", features).focus();
  },
  showInstallDialog: function() {
      var features = "resizeable=yes,titlebar,centerscreen";
      var url = "chrome://moodmill/content/wizard.xul";
      window.openDialog(url, "moodmill_install", features).focus();
  },
  showMessages: function() {
      var features = "resizeable=yes,titlebar,toolbar,centerscreen,modal,width=300,height=300";
      var url = "chrome://moodmill/content/messages.xul";
      var param = { 'input' : this.messages, 'output' : false } ;
      window.openDialog(url, "moodmill_messages", features, param).focus();
      if (param.output)
        this.clearMessages();
  },
  getAuthObject: function() {
    YAHOO.MoodMill.Account.setAccountURI(YAHOO.MoodMill.Account.moodmillExtensionURI);
    var auths = YAHOO.MoodMill.Account.getAllAuthInfo();
    if (auths)
        return auths[0];
    else
        return null;
  },
  upgrade: function() {
    // update to new security method
    var username = YAHOO.MoodMill.Preference.getString('extensions.moodmill.username', null);
    var userpass = YAHOO.MoodMill.Preference.getString('extensions.moodmill.password', null);
    
    if ((username =='already-upgraded-to-new-version') && (userpass =='already-upgraded-to-new-version')) {
        Logger.log("No upgrade needed");
        return;
    } else {
        Logger.log("Upgrading to new version");
        YAHOO.MoodMill.Account.update(username, userpass);
    }
    
    YAHOO.MoodMill.Preference.setString('extensions.moodmill.username', 'already-upgraded-to-new-version');
    YAHOO.MoodMill.Preference.setString('extensions.moodmill.password', 'already-upgraded-to-new-version');
  },
  appendMessage: function(msg) {
    var date = new Date();
    this.messages.push( { 'timestamp': date, 'message': msg} );
    Logger.log("[" + date + "] " + msg);
    this.showNotification(true);
  },
  clearMessages: function() {
    this.messages = new Array();
    this.showNotification(false);
  },
  showNotification: function(show) {
    var el = document.getElementById('moodmill-error-image');
    if (show)
        el.style.display = 'block';
    else
        el.style.display = 'none';
  },
  isInstalled: function() {
    var username = YAHOO.MoodMill.Preference.getString('extensions.moodmill.username', null);
    var userpass = YAHOO.MoodMill.Preference.getString('extensions.moodmill.password', null);
    
    var res = ((username != null) && (userpass != null));
    Logger.log("isInstalled? " + (res==true?"Yes":"No"));
    return res;
  }/*,
  factory: function() {
  }*/
};

var moodmill = new MoodMill();

window.addEventListener("load", function(e) { moodmill.onLoad(e); }, false);
}